<template>
  <view class="container">
    <!-- 商品展示区（放在最上方） -->
    <view v-if="cart.length" class="cart-list">
      <view class="cart-title">商品清单</view>
      <view class="cart-item" v-for="item in cart" :key="item.id">
        <image :src="item.internalServiceImage || item.productImage" class="cart-item-img" />
        <view class="cart-item-info">
          <text class="cart-item-name">{{ item.serviceName || item.productName }}</text>
          <text class="cart-item-qty">x{{ item.quantity }}</text>
          <text class="cart-item-price">¥{{ item.price }}</text>
        </view>
      </view>
    </view>

    <!-- 添加通知栏 -->
    <view v-if="noticeContent" class="notice-bar">
      <text class="notice-text">{{ noticeContent }}</text> 
    </view>

    <view class="payment-card">
      <view class="user-info">
        <view class="info-item">
          <text class="label">联系人:</text>
          <input type="text" v-model="userInfo.name" placeholder="请输入联系人姓名" />
        </view>
        <view class="info-item">
          <text class="label">电话:</text>
          <input type="number" v-model="userInfo.phone" placeholder="请输入联系电话" />
        </view>
        <!-- 地址多列选择 -->
        <view class="info-item">
          <text class="label">地址:</text>
          <picker mode="multiSelector" :range="addressList" @change="onAddressChange">
            <view class="uni-input">
              {{ userInfo.address || '请选择楼号/层号/房间号' }}
            </view>
          </picker>
        </view>
        <!-- 送货日期 -->
        <!-- <view class="info-item">
          <text class="label">送货日期:</text>
          <picker 
            mode="date" 
            :value="selectedDate" 
            :start="startDate" 
            :end="endDate" 
            fields="day" 
            @change="bindDateChange"
          >
            <view class="uni-input">{{ selectedDate || '请选择送货日期' }}</view>
          </picker>
        </view> -->
        <!-- 送货时间 -->
        <!-- <view class="info-item">
          <text class="label">送货时间:</text>
          <picker mode="time" :value="selectedTime" @change="bindTimeChange">
            <view class="uni-input">{{ selectedTime || '请选择送货时间' }}</view>
          </picker>
        </view> -->
      </view>
    </view>

    <view class="payment-button" @click="handlePayment">
      立即支付
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { getPrepayId, createProduceOrder, getHospitalAddressList } from '@/api/wxlogin/wxlogin'
import { getNoticeList } from '@/api/content/banner'
const userInfo = ref({
  name: '',
  phone: '',
  address: ''
})
const cart = ref([])
const hospitalName = ref('')
const rooms = ref([]) // 添加这行，用于存储医院房间数据
const noticeContent = ref('')

// 多列地址选择数据
const addressList = ref([[], [], []]) // [楼号[], 层号[], 房间号[]]
const addressData = ref({}) // 存储完整的地址数据结构

// 处理地址选择器变化
const onAddressChange = (e) => {
  const sel = e.detail.value;
  const currentBuilding = addressList.value[0][sel[0]]?.replace('号楼', '');
  const currentFloor = addressList.value[1][sel[1]]?.replace('层', '');
  const currentRoom = addressList.value[2][sel[2]]?.replace('房间', '');

  // 更新选中的地址文本
  if (currentBuilding && currentFloor && currentRoom) {
    userInfo.value.address = `${currentBuilding}号楼 ${currentFloor}层 ${currentRoom}房间`;
  }
}

// 送货日期选择
const pad = n => n < 10 ? '0' + n : n

// 获取指定天数后的日期字符串
function getDateStr(baseDate, offset) {
  const d = new Date(baseDate)
  d.setDate(d.getDate() + offset)
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
}

// 判断当前时间是否超过17:00
const isAfterEndTime = () => {
  const now = new Date()
  return now.getHours() > 17 || (now.getHours() === 17 && now.getMinutes() > 0)
}

const today = new Date()
const dateOptions = ref([])

if (isAfterEndTime()) {
  // 超过17:00，只能选明天和后天
  dateOptions.value = [
    getDateStr(today, 1),
    getDateStr(today, 2)
  ]
} else {
  // 否则可选今天、明天、后天
  dateOptions.value = [
    getDateStr(today, 0),
    getDateStr(today, 1),
    getDateStr(today, 2)
  ]
}
const selectedDate = ref(dateOptions.value[0])

// 时间选项
const selectedTime = ref('')
const timeOptions = ref([])

function getTimeOptions(dateStr) {
  const result = []
  let startHour = 8, startMinute = 30
  let endHour = 17, endMinute = 0

  // 今天：起始时间为当前时间+20分钟，向上取整到5分钟
  if (dateStr === dateOptions[0]) {
    const now = new Date()
    now.setMinutes(now.getMinutes() + 20)
    let hour = now.getHours()
    let minute = now.getMinutes()
    minute = Math.ceil(minute / 5) * 5
    if (minute === 60) {
      hour += 1
      minute = 0
    }
    if (hour < 8 || (hour === 8 && minute < 30)) {
      hour = 8
      minute = 30
    }
    startHour = hour
    startMinute = minute
  }

  // 生成时间段
  let h = startHour, m = startMinute
  while (h < endHour || (h === endHour && m <= endMinute)) {
    const label = `${pad(h)}:${pad(m)}`
    result.push(label)
    m += 5
    if (m >= 60) {
      h += 1
      m = 0
    }
  }
  return result
}

// 监听日期变化
const onDateChange = (e) => {
  selectedDate.value = dateOptions.value[e.detail.value]
  timeOptions.value = getTimeOptions(selectedDate.value)
  selectedTime.value = timeOptions.value[0] || ''
}

// 页面初始化
timeOptions.value = getTimeOptions(selectedDate.value)
selectedTime.value = timeOptions.value[0] || ''

onLoad(async (options) => {
   
  if (options.cart) {
    cart.value = JSON.parse(decodeURIComponent(options.cart))
  }

  // 从storage中获取当前医院名称
  const currentHospital = uni.getStorageSync('currentHospital')
  console.log('当前医院名称:', currentHospital)
  // 获取全部医院地址数据
  const res = await getHospitalAddressList()
  console.log('获取到的医院地址数据:', res)
  if (res.code === 200 && Array.isArray(res.data)) {
    if (!currentHospital) {
      uni.showToast({
        title: '请先选择医院',
        icon: 'none'
      })
      return
    }

    // 过滤出当前医院的所有房间数据
    rooms.value = res.data.filter(h => {
      return h.hospitalName === currentHospital &&
             h.building && 
             h.floor && 
             h.roomNumber;
    });

    if (rooms.value.length === 0) {
      uni.showToast({
        title: '该医院暂无可用房间',
        icon: 'none'
      })
      return
    }

    // 初始化选择器数据 - 直接获取所有可能的值
    const buildings = [...new Set(rooms.value.map(room => room.building))]
      .sort()
      .map(b => b + '号楼');
    
    const floors = [...new Set(rooms.value.map(room => room.floor))]
      .sort()
      .map(f => f + '层');
    
    const roomNumbers = [...new Set(rooms.value.map(room => room.roomNumber))]
      .sort()
      .map(r => r + '房间');

    // 一次性设置所有列的数据
    addressList.value = [buildings, floors, roomNumbers];
  }

  // 自动填充联系人和电话
  const storedUserInfo = uni.getStorageSync('userInfo')
  if (storedUserInfo) {
    try {
      const info = JSON.parse(storedUserInfo)
      userInfo.value.name = info.name || ''
      userInfo.value.phone = info.phoneNumber || ''
    } catch (e) {
      // 解析失败不处理
    }
  }

  // 获取通知内容
  const noticeRes = await getNoticeList({ page: 1, pageSize: 1 })
  if (noticeRes.code === 200 && noticeRes.data.list && noticeRes.data.list.length > 0) {
    noticeContent.value = noticeRes.data.list[0].content || ''
  }
})

const fetchNotice = async () => {
  try {
    const res = await getNoticeList()
    if (res.code === 200 && Array.isArray(res.data)) {
      const type3Notice = res.data.find(item => item.noticeId === 3)
      if (type3Notice) {
        noticeContent.value = type3Notice.notice
      }
    }
  } catch (err) {
    console.error('获取通知失败:', err)
  }
}

// 在 onLoad 中调用获取通知
onLoad(async (options) => {
  // ...existing onLoad code...
  await fetchNotice()
})

const handlePayment = async () => {
  // 校验必填信息
  if (!userInfo.value.name?.trim()) {
    uni.showToast({
      title: '请输入联系人姓名',
      icon: 'none'
    });
    return;
  }

  // 校验手机号格式
  const phoneReg = /^1[3-9]\d{9}$/;
  if (!phoneReg.test(userInfo.value.phone)) {
    uni.showToast({
      title: '请输入正确的手机号',
      icon: 'none'
    });
    return;
  }

  // 校验地址选择
  if (!userInfo.value.address?.trim()) {
    uni.showToast({
      title: '请选择送货地址',
      icon: 'none'
    });
    return;
  }

  // 校验商品数据
  if (!cart.value.length) {
    uni.showToast({
      title: '购物车为空',
      icon: 'none'
    });
    return;
  }

  try {
    // 1. 生成订单参数
    const outTradeNo = Date.now().toString() + Math.floor(1000 + Math.random() * 9000); // 时间戳+4位随机数
    const productList = cart.value
      .map(item => `${item.serviceName || item.productName} x${item.quantity}`)
      .join(' -- ');
    const wxUserId = uni.getStorageSync('userId');
    const amount = cart.value.reduce((sum, item) => sum + item.price * item.quantity, 0);

    // 2. 创建商品订单
    await createProduceOrder({
      wxUserId,
      phone: userInfo.value.phone,
      name: userInfo.value.name,
      address: userInfo.value.address,
      amount,
      outTradeNo,
      productList
    });

    // 3. 获取prepay_id并调起支付
    const description = cart.value.map(item => item.serviceName || item.productName).join('、');
    const openid = uni.getStorageSync('openid');
    const prepayRes = await getPrepayId({
      serviceName: description,
      totalPrice: amount,
      openid,
      outTradeNo
    });

    if (prepayRes.code === 200 && prepayRes.data) {
      const payParams = {
        timeStamp: prepayRes.data.timeStamp,
        nonceStr: prepayRes.data.nonceStr,
        package: prepayRes.data.package,
        signType: prepayRes.data.signType,
        paySign: prepayRes.data.paySign
      }
      wx.requestPayment({
        ...payParams,
        success: (res) => {
          uni.showToast({
            title: '支付成功',
            icon: 'success',
            duration: 2000
          })
          setTimeout(() => {
            uni.navigateBack({
            delta: 1 // 返回上一页
        })
          }, 2000)
        },
        fail: (err) => {
          uni.showToast({
            title: '支付失败',
            icon: 'none',
            duration: 2000
          })
        }
      })
    } else {
      throw new Error(prepayRes.message || '获取支付信息失败')
    }
  } catch (err) {
    uni.showToast({
      title: err.message || '支付失败',
      icon: 'none'
    })
  }
}
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 32rpx;
}

.cart-list {
  background: #fff;
  border-radius: 20rpx;
  margin-bottom: 32rpx;
  padding: 32rpx 24rpx 16rpx 24rpx;
  box-shadow: 0 4rpx 16rpx rgba(255,204,0,0.08);

  .cart-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 24rpx;
    letter-spacing: 2rpx;
  }

  .cart-item {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;
    padding-bottom: 16rpx;
    border-bottom: 1rpx solid #f0f0f0;

    &:last-child {
      border-bottom: none;
      margin-bottom: 0;
      padding-bottom: 0;
    }

    .cart-item-img {
      width: 120rpx;
      height: 120rpx;
      border-radius: 16rpx;
      margin-right: 24rpx;
      object-fit: cover;
      box-shadow: 0 2rpx 8rpx rgba(255,204,0,0.08);
      background: #faf8f0;
    }

    .cart-item-info {
      flex: 1;
      display: flex;
      align-items: center;

      .cart-item-name {
        font-size: 30rpx;
        color: #222;
        flex: 1;
        font-weight: 500;
      }

      .cart-item-qty {
        font-size: 28rpx;
        color: #888;
        margin: 0 18rpx;
      }

      .cart-item-price {
        font-size: 30rpx;
        color: #ff6b6b;
        font-weight: bold;
      }
    }
  }
}

.notice-bar {
  background-color: #fffbe6;
  padding: 24rpx;
  border-radius: 16rpx;
  margin-bottom: 32rpx;
  display: flex;
  align-items: center;
  box-shadow: 0 4rpx 16rpx rgba(255,204,0,0.08);

  .notice-text {
    font-size: 28rpx;
    color: #333;
    line-height: 1.5;
  }
}

.payment-card {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 32rpx;
  margin-bottom: 32rpx;

  .service-info {
    border-bottom: 2rpx solid #eee;
    padding-bottom: 24rpx;
    margin-bottom: 24rpx;

    .service-name {
      font-size: 32rpx;
      color: #333;
      margin-bottom: 16rpx;
      display: block;
    }

    .service-price {
      font-size: 36rpx;
      color: #ff6b6b;
      font-weight: bold;
    }
  }

  .user-info {
    .info-item {
      margin-bottom: 24rpx;

      .label {
        font-size: 28rpx;
        color: #666;
        margin-bottom: 8rpx;
        display: block;
      }

      input {
        width: 100%;
        height: 80rpx;
        background-color: #f5f5f5;
        border-radius: 8rpx;
        padding: 0 24rpx;
        font-size: 28rpx;
      }
    }
  }
}

.payment-button {
  background-color: #ffcc00;
  color: #333;
  font-size: 32rpx;
  font-weight: bold;
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  border-radius: 44rpx;
  margin-top: 48rpx;
  box-shadow: 0 4rpx 16rpx rgba(255,204,0,0.08);

  &:active {
    opacity: 0.8;
  }
}
</style>
